<template>
  <div id="div1">
    <div id="div1-1">
      <vxe-button class="div1-1-button1" @click="addUser">新增用户</vxe-button>
      <vxe-button class="div1-1-button2" @click="delUser">删除用户</vxe-button>
      <vxe-button class="div1-1-button3" @click="saveUser">保存</vxe-button>
    </div>
    <div id="div1-2">
      <vxe-table keep-source ref="t1Ref" height="100%"
                 :edit-config="{ trigger: 'click', mode: 'cell',activeMethod:()=>true }"
                 @checkbox-change="changeUser" :checkbox-config="{ highlight: true }" auto-resize :data="tableData">
        <vxe-table-column type="checkbox" width="60"></vxe-table-column>
        <vxe-table-column type="seq" width="60"></vxe-table-column>
        <vxe-table-column field="username" title="用户名" width="100" :edit-render="{
                                immediate: true,
                                name: 'input',
                                attrs: {type: 'text'}

        }">
        </vxe-table-column>

        <vxe-table-column align="center" header-align="center" field="name" title="姓名" width="100" :edit-render="{
                                immediate: true,
                                name: 'input',
                                attrs: {type: 'text'},
                                events: {
                                }
                              }">
        </vxe-table-column>
        <vxe-table-column field="sex" title="性别" width="100" :edit-render="{
                               immediate: true,
                                name: '$select',
                                props: {type: 'select'},
                                options: ageOptions,
                                events: {
                                }
        }"></vxe-table-column>
        <vxe-table-column field="age" title="年龄" width="100" :edit-render="{
                                immediate: true,
                                name: 'input',
                                attrs: {type: 'text'}
        }"></vxe-table-column>
        <vxe-table-column field="phone" title="手机号" width="150" :edit-render="{
                                immediate: true,
                                name: 'input',
                                attrs: {type: 'text'}
        }"></vxe-table-column>
        <vxe-table-column field="idcard" title="身份证号" width="280" :edit-render="{
                                immediate: true,
                                name: 'input',
                                attrs: {type: 'text'}
        }"></vxe-table-column>
        <vxe-table-column field="place" title="家庭住址" width="280" :edit-render="{
                                immediate: true,
                                name: 'input',
                                attrs: {type: 'text'}
        }"></vxe-table-column>
        <vxe-table-column field="email" title="邮件" width="280" :edit-render="{
                                immediate: true,
                                name: 'input',
                                attrs: {type: 'text'}
        }"></vxe-table-column>
        <vxe-table-column field="status" title="状态" width="100" :edit-render="{
                                immediate: true,
                                name: '$select',
                                props: {type: 'select'},
                                options: statusOptions,
                                events: {
                                }
        }"></vxe-table-column>
        <vxe-table-column align="center" header-align="center" :width="300" title="操作">
          <template slot-scope="scope">
            <div style="text-align: center;width: 100%;">
              <el-button size="mini" @click="info(scope)">详情</el-button>
              <el-button size="mini" @click="selectRole(scope)">角色</el-button>
            </div>
          </template>
        </vxe-table-column>
      </vxe-table>
    </div>
    <el-dialog title="选择角色" :visible.sync="selectRoleShow" center>
      <el-table ref="t2Ref" :data="roleData" class="basic-table" max-height="300" @selection-change="changeRole">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column property="rolename" label="角色名称" width="150"></el-table-column>
        <el-table-column property="description" label="地址"></el-table-column>
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="selectRoleShow = false">取 消</el-button>
        <el-button type="primary" @click="saveUserRoles">确 定</el-button>
      </div>
    </el-dialog>
  </div>

</template>

<script>
import request from '@/utils/request'

export default {
  name: "AssetList",
  data() {
    return {
      ageOptions: [
        {label: '男', value: '0'},
        {label: '女', value: '1'},
      ],
      statusOptions: [
        {label: '正常', value: '1'},
        {label: '禁用', value: '0'},
      ],
      // 用户表
      tableData: [
        {
          id: '1',
          username: 'lwx',
          name: '刘文轩',
          sex: '0',
          age: '28',
          place: '南京市悦城花园',
          phone: '1372234334',
          idcard: '320123199012312345',
          email: 'lwx@163.com',
          status: '0'
        },
      ],
      // 选中的用户
      selectedData: [],
      // 点击操作列按钮时，记录点击的用户
      selectedUser: '',
      // 选择角色的对话框是否显示
      selectRoleShow: false,
      // 角色表
      roleData: [],
      // 选中的角色
      changedRoles:[],
    }
  },
  mounted() {
    this.loadData();
    this.loadRoleData();
  },
  computed: {},
  methods: {
    addUser() {
      const self = this;
      self.$refs.t1Ref.insertAt({}, -1);
      // this.tableData.push({seq: this.tableData.length + 1, type: '', code: '', amount: 0})
    },
    delUser() {
      const self = this;
      self.$refs.t1Ref.removeCheckboxRow();
    },
    changeUser({records}) {
      this.selectedData = records;
      console.log('rows', JSON.stringify(records))
    },
    changeAllUser(records) {
      console.log('all', JSON.stringify(records));
    },
    loadData() {
      request({
        url: '/user/user',
        method: 'get',
      }).then(response => {
        if (response && response.data) {
          console.log('response', response);
          const tempList = [];
          response.data.records.forEach(item => {
            tempList.push({
              id: item.id,
              name: item.name,
              username: item.username,
              sex: item.sex,
              age: item.age,
              phone: item.phone,
              idcard: item.idcard,
              place: item.place,
              email: item.email,
              status: item.status
            })
          })
          this.tableData = tempList;
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('加载数据失败')
      })
    },
    saveUser() {
      const self = this;
      console.log('t1Ref', JSON.parse(JSON.stringify(self.$refs.t1Ref.getRecordset())));
      const {
        insertRecords,
        updateRecords,
        removeRecords
      } = JSON.parse(JSON.stringify(self.$refs.t1Ref.getRecordset()));
      request({
        url: '/user/user/batch',
        method: 'post',
        data: {
          insertAndUpdate: updateRecords.concat(insertRecords),
          del: removeRecords
        }
      }).then(response => {
        if (response && response.data) {
          this.$message.success('保存成功');
          this.loadData();
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('保存失败')
      })
    },
    info(scope){
      console.log('info', scope);
    },
    loadRoleData(callBack){
      request({
        url: '/user/role',
        method: 'get',
      }).then(response => {
        if (response && response.data) {
          const tempList = [];
          response.data.records.forEach(item => {
            tempList.push({
              id: item.id,
              rolename: item.rolename,
              description: item.description,
              status: item.status
            })
          })
          this.roleData = tempList;
        }
        if (callBack && typeof callBack === 'function') {
          callBack();
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('加载数据失败')
      })
    },
    // 角色选择按钮
    selectRole(scope) {
      const self = this;
      // 保存操作的用户信息
      self.selectedUser = scope.row;
      self.loadRoleData(() => {
        // 打开弹窗
        self.selectRoleShow = true;
        this.$nextTick(() => {
          // 先清空现有选择
          self.$refs.t2Ref.clearSelection();
          // 获取用户下角色
          request({
            url: '/user/userRole',
            method: 'get',
            params: {
              userId: scope.row.id,
              size: -1
            },
          }).then(response => {
            if (response && response.data) {
              const roleIds= response.data.records.map(item => item.roleId);
              self.roleData.forEach(row => {
                if (roleIds.includes(row.id)){
                  this.$refs.t2Ref.toggleRowSelection(row, true);
                }
              })
            }
          }).catch(error => {
            console.log('error', error);
            this.$message.error('加载数据失败')
          });
        });
      });
    },
    changeRole(val){
      const self = this;
      self.changedRoles = val;
    },
    saveUserRoles(){
      const self = this;
      const userId = self.selectedUser.id;
      const userRoles = self.changedRoles.map(item => {
        return {
          userId: userId,
          roleId: item.id
        }
      });
      request({
        url: '/user/userRole/batch',
        method: 'post',
        data: userRoles
      }).then(response => {
        if (response && response.data) {
          this.$message.success('保存成功');
          self.selectRoleShow = false;
        }
      }).catch(error => {
        console.log('error', error);
        this.$message.error('保存失败')
      })
    }
  }
}
</script>

<style scoped>
#div1 {
  width: 100%;
  height: 100%;
  position: relative;
}

#div1-1 {
  width: 100%;
  height: 10%;
  margin-bottom: 10px;
  position: relative;
  overflow: hidden;
}

.div1-1-button1 {
  top: 20px;
  right: 20px;
  width: 80px;
  position: absolute;
}

.div1-1-button2 {
  top: 20px;
  right: 120px;
  position: absolute;
  width: 80px;
}

.div1-1-button3 {
  top: 20px;
  right: 230px;
  position: absolute;
  width: 80px;
}

#div1-2 {
  width: 100%;
  height: Calc(90% - 10px);
  background-color: #606376;
  border-radius: 10px;
  padding: 10px;
  position: absolute;
}


#div1-2 .vxe-table {
}

::v-deep .vxe-table--header-wrapper {
  background-color: #606376 !important;
}

::v-deep .vxe-table--header-wrapper .vxe-header--row {
  background-color: #606376 !important;
  color: white;
}

::v-deep .vxe-table--body-wrapper {
  background-color: #606376 !important;
}

::v-deep .vxe-table--body-wrapper .vxe-body--row {
  background-color: #606376 !important;
  color: white;
}

::v-deep .el-dialog__header {
  background-color: #313A63;
  border-bottom: 1px solid #d9d9d9;
}

::v-deep .el-dialog__header .el-dialog__title {
  color: #FFFFFF;
}

::v-deep .el-dialog__body {
  background-color: #313A63;
  border-bottom: 1px solid #d9d9d9;
}

/* 可选：修改底部按钮区背景 */
::v-deep .el-dialog__footer {
  background-color: #313A63;
}

/* 表格头部背景 */
::v-deep .basic-table .el-table__header-wrapper th {
  background-color: #606376;
  color: #FFFFFF;
}

::v-deep .basic-table .el-table__body tr:hover > td {
  background-color: #3C4567 !important; /* 浅蓝色背景 */
}

/* 表格内容区背景 */
::v-deep .basic-table .el-table__body-wrapper td {
  background-color: #606376;
  color: #FFFFFF;
}



</style>